package com.funwell.modules.service.systask;


import com.ace.cache.service.impl.RedisServiceImpl;
import com.funwell.modules.controller.request.systask.SysTaskRequestBean;
import com.funwell.server.constants.Errors;
import com.funwell.server.utils.ExceptionUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysTaskService {
    private static final Logger logger =  LoggerFactory.getLogger(SysTaskService.class);

    @Autowired
    private RedisServiceImpl redisService;


    @Resource(name = "scheduler")
    private Scheduler scheduler;

/*    *//**
     * 获取任务调试列表
     * @param pageIndex
     * @param pageSize
     * @return
     *//*
    public List<HScheduleTrigger> taskList(long pageIndex, long pageSize){
        List<String> triggerList=redisService.lrange("HCRM_TASK",(pageIndex-1)*pageSize,(pageIndex-1)+pageSize);
        return JSONArray.redisService.toJavaObjectList(triggerList,HScheduleTrigger.class);
    }*/

    /**
     * 新增定时任务
     * @param scheduleJob
     */
    public void  add(SysTaskRequestBean scheduleJob){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            JobDataMap dataMap=new JobDataMap();
            dataMap.put("data",scheduleJob.getJobData());
            JobDetail jobDetail= JobBuilder.newJob((Class<? extends Job>) Class.forName(scheduleJob.getJobName()))
                    .withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).setJobData(dataMap).build();

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob
                    .getCron());

            //按新的cronExpression表达式构建一个新的trigger
            trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(scheduleBuilder).build();


            //把trigger和jobDetail注入到调度器
            scheduler.scheduleJob(jobDetail, trigger);

        } catch (ClassNotFoundException e) {
            logger.error("没有发现相关任务类，或任务类无效：{}",e.getMessage());
        } catch (SchedulerException e) {
            logger.error("任务新增执行失败：{}",e.getMessage());
        }
    }

    /**
     * 删除定时任务
     * @param scheduleJob
     */
    public void detele(SysTaskRequestBean scheduleJob){
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            logger.error("任务删除执行失败：{}",e.getMessage());
        }
    }

    /**
     * 更新定时任务
     * @param scheduleJob
     */
    public void update(SysTaskRequestBean scheduleJob){
        TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        //表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule( scheduleJob.getCron());

        //按新的cronExpression表达式重新构建trigger
        CronTrigger trigger = null;
        try {
            trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if(trigger==null){
                ExceptionUtil.throwException(Errors.TASK_NOT_TRIGGER);
            }else{
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder).build();
                //按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
            }

        } catch (SchedulerException e) {
            logger.error("任务更新执行失败：{}",e.getMessage());
        }
    }

    /**
     * 暂停任务
     * @param scheduleJob
     */
    public void pause(SysTaskRequestBean scheduleJob){
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            logger.error("任务暂停执行失败：{}",e.getMessage());
        }
    }


    /**
     * 恢复任务
     * @param scheduleJob
     */
    public void resume(SysTaskRequestBean scheduleJob){
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            logger.error("任务恢复执行失败：{}",e.getMessage());
        }
    }

    /**
     * 立即执行任务
     * @param scheduleJob
     */
    public void immediately(SysTaskRequestBean scheduleJob){
        JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
        try {

            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            logger.error("任务立即执行失败：{}",e.getMessage());
            e.printStackTrace();
        }
    }



    
}
